package com.lechi.web.framework.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 对JOb操作的核心类
 */
@Slf4j
@Component
public final class DynamicSchedulerFactory {

    @Autowired
    private Scheduler scheduler;

    /**
     * Register a job
     * 添加(注册)一个动态的JOB
     *
     * @param job DynamicJob
     * @return True is register successful
     * @throws SchedulerException e
     */
    public boolean registerJob(DynamicJob job, Date startTime) throws SchedulerException {
        final TriggerKey triggerKey = job.triggerKey();
        if (scheduler.checkExists(triggerKey)) {
            final Trigger trigger = scheduler.getTrigger(triggerKey);
            throw new SchedulerException("Already exist trigger [" + trigger + "] by key [" + triggerKey + "] in Scheduler");
        }

        final Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(Integer.parseInt(job.cronExpression()))
                        .repeatForever()).startAt(startTime).build();

        final JobDetail jobDetail = job.jobDetail();
        final Date date = scheduler.scheduleJob(jobDetail, trigger);

        log.debug("注册动态job {} on {}", job, date);
        return true;
    }

    /**
     * Pause exist job
     * 暂停已经存在的JOB
     */
    public boolean pauseJob(DynamicJob existJob) throws SchedulerException {
        final TriggerKey triggerKey = existJob.triggerKey();
        boolean result = false;
        if (scheduler.checkExists(triggerKey)) {
            scheduler.pauseTrigger(triggerKey);
            result = true;
            log.debug("Pause exist DynamicJob {}, triggerKey [{}] successful", existJob, triggerKey);
        } else {
            log.debug("Failed pause exist DynamicJob {}, because not fount triggerKey [{}]", existJob, triggerKey);
        }
        return result;
    }


    /**
     * Resume exist job
     * 重启一个JOB
     */
    public boolean resumeJob(DynamicJob existJob) throws SchedulerException {
        final TriggerKey triggerKey = existJob.triggerKey();
        boolean result = false;
        if (scheduler.checkExists(triggerKey)) {
            final CronTrigger newTrigger = existJob.cronTrigger();
            final Date date = scheduler.rescheduleJob(triggerKey, newTrigger);

            result = true;
            log.debug("Resume exist DynamicJob {}, triggerKey [{}] on [{}] successful", existJob, triggerKey, date);
        } else {
            log.debug("Failed resume exist DynamicJob {}, because not fount triggerKey [{}]", existJob, triggerKey);
        }
        return result;
    }


    /**
     * Checking the job is existed or not
     * 检查JOB是否存在
     *
     * @param job Job
     * @return True is existed, otherwise false
     * @throws SchedulerException e
     */
    public boolean existedJob(DynamicJob job) throws SchedulerException {
        final TriggerKey triggerKey = job.triggerKey();
        return scheduler.checkExists(triggerKey);
    }


    /**
     * Remove exists job
     * 删除一个已经存在的JOB
     *
     * @param existJob A  DynamicJob which exists in Scheduler
     * @return True is remove successful
     * @throws SchedulerException e
     */
    public boolean removeJob(DynamicJob existJob) throws SchedulerException {
        final TriggerKey triggerKey = existJob.triggerKey();
        boolean result = false;
        if (scheduler.checkExists(triggerKey)) {
            result = scheduler.unscheduleJob(triggerKey);
        }

        log.error("Remove DynamicJob {} result [{}]", existJob, result);
        return result;
    }
}